package eiisan.crypto.demo;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 摘要
 */
public class SHAXDemo {

    public static void main(String[] args) {
        String content = "Hello";
        jdkSHA1(content);
        ccsha(content);
        bcHmacMd5(content);
    }

    /**
     * JDK实现方式（同样是使用MessageDigest）
     * @param src
     */
    public static void jdkSHA1(String src){
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA");
            digest.update(src.getBytes());
            System.out.println("JDK SHA1:"+ Hex.encodeHexString(digest.digest()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * cc的实现方式
     * @param src
     */
    public static void ccsha(String src){
        System.out.println("CC  SHA1:"+ DigestUtils.sha1Hex(src));
    }

    /**
     * BC方式
     */
    public static void bcHmacMd5(String src){

        HMac hMac=new HMac(new MD5Digest());
        hMac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));  //需要十位密钥
        hMac.update(src.getBytes(),0,src.getBytes().length);

        byte[] hmacMD5=new byte[hMac.getMacSize()];
        hMac.doFinal(hmacMD5, 0);
        System.out.println("bc hmacMD5: "+org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5));

    }

}